package com.linkstec.szkettle;

import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class CarteKettleRunTest{
	private static final Logger logger = LogManager.getLogger(CarteKettleRunTest.class);
	private static final HttpClient httpClient;
	private static Integer pos = 0;
	private static Map<String,Integer> serverBaseMap = new HashMap<String, Integer>();
	private static Map<String,Integer> serverWeightMap = new HashMap<String, Integer>();
	static {
        RequestConfig config = RequestConfig.custom().setSocketTimeout(15000).setConnectTimeout(60000).setConnectionRequestTimeout(600000).build();
        httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
        // http://192.168.10.141:8085=1,http://192.168.10.143:8085=2
        String  carteServers = "http://192.168.10.141:8085=1,http://192.168.10.143:8085=2";
        String[] carteServersArr = carteServers.split(",");
        for (String carteServer : carteServersArr) {
			String[] carteServerArr = carteServer.split("=");
			// 服务器地址 权重
			serverBaseMap.put(carteServerArr[0], Integer.parseInt(carteServerArr[1]));
			serverWeightMap.put(carteServerArr[0], Integer.parseInt(carteServerArr[1]));
		}
        /*new Thread(new Runnable() {
        	public void run() {
        		while (true) {
        			Set<String> keySet = serverBaseMap.keySet();
        			for (String server : keySet) {
        				String status = carteStatus(server);
        				if ("Online".equals(status)) {
        					logger.info(server + "服务正常");
        					serverWeightMap.put(server,serverBaseMap.get(server));
        				} else {
        					logger.error(server + "服务不正常，下线");
        					serverWeightMap.remove(server);
        				}
        			}
        			try {
        				Thread.sleep(60000);
        			} catch (InterruptedException e) {
        				e.printStackTrace();
        			}
        		}
        	}
        }).start();*/
    }

	/**
	 * 
	 */
	public static String getServer() {

        //重新创建一个Map，避免出现由于服务器上线和下线导致的并发问题
        Map<String,Integer> serverMap=new HashMap<String,Integer>();
        serverMap.putAll(serverWeightMap);

        //取得carte地址的list
        Set<String> keySet=serverMap.keySet();
        Iterator<String> it=keySet.iterator();
        List<String> serverList=new ArrayList<String>();

        while (it.hasNext()) {
            String server=it.next();
            Integer weight= (Integer) serverMap.get(server);//权重
            for (int i = 0; i < weight; i++) {
                serverList.add(server);
            }
        }
        String server=null;
        //同步
        synchronized (pos) {
        	if(pos>=serverList.size()) {
        		pos=0;
        	}
        	server=serverList.get(pos);
        	pos++;
        }
        return server;
	}

	/**
	 * 
	 * 运行转换用runTrans
	 * @param transName
	 * @return id
	 */
	public static String runTrans(String carte, String transName) {
		
		String id = null;
		try {
//			String kettle = "http://localhost:8085";
			carte = "http://192.168.10.141:8085";
			//获取kettle的URL
			String urltemp = carte + "/kettle/runTrans/?trans=";
			String urltemp1 = transName;
	        String uri = urltemp + urltemp1;
	        HttpGet get = new HttpGet(uri);
	        logger.info(uri);
	        //添加http头信息
	        get.addHeader("Authorization", "Basic Y2x1c3RlcjpjbHVzdGVy");
//	        get.setHeader("Cache-Control", "max-age=0");
//	        get.addHeader("User-Agent","your agent");
	        HttpResponse response;
	        response = httpClient.execute(get);
	        int code = response.getStatusLine().getStatusCode();
	        //检验状态码，如果成功接收数据
	        if (code == 200) {
	            String rev = EntityUtils.toString(response.getEntity());
	            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  
                DocumentBuilder builder = factory.newDocumentBuilder();  
                ByteArrayInputStream is = new ByteArrayInputStream(rev.getBytes());
                Document doc = builder.parse(is);
                NodeList nodeList = doc.getElementsByTagName("result");
                NodeList idList = doc.getElementsByTagName("id");
                Node node = nodeList.item(0);
                Node idnode = idList.item(0);
                id = idnode.getTextContent();
                logger.info(node.getTextContent());
                logger.info(id);
                logger.info(response);
                logger.info(transName + "启动成功" +rev);
                
	        }
	    } catch (Exception e) {
	    	logger.error("出错了" + e.getMessage());
	    }
		return id;
	}
	
	/**
	 * 
	 * 运行转换用runTrans
	 * @param transName
	 * @return status
	 */
	public static String transStatus(String carte, String transName, String transId) {
		String result = "";
		try {
			carte = "http://192.168.10.141:8085";
			//获取kettle的URL
			String urltemp = carte + "/kettle/transStatus/?xml=Y&name=";
			//目标URL    Transformation name
			String urltemp1 = transName;
			String id ="";
			if(StringUtils.isNotBlank(transId)) {
				id = "&id=" +transId;
			}
			String uri = urltemp + urltemp1 + id;
			HttpGet get = new HttpGet(uri);
			logger.info(uri);
			//添加http头信息
			get.addHeader("Authorization", "Basic Y2x1c3RlcjpjbHVzdGVy");
//	        get.setHeader("Cache-Control", "max-age=0");
//	        get.addHeader("User-Agent","your agent");
			HttpResponse response;
			response = httpClient.execute(get);
			int code = response.getStatusLine().getStatusCode();
			//检验状态码，如果成功接收数据
			if (code == 200) {
				String rev = EntityUtils.toString(response.getEntity());
				DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  
				DocumentBuilder builder = factory.newDocumentBuilder();  
				ByteArrayInputStream is = new ByteArrayInputStream(rev.getBytes());
				Document doc = builder.parse(is);
				NodeList nodeList = doc.getElementsByTagName("status_desc");
				Node node = nodeList.item(0);
				result = node.getTextContent();
				logger.info(transName + "转换状态是：" + node.getTextContent());
				logger.info(id);
				logger.info(response);
				logger.info(rev);
				
			}
		} catch (Exception e) {
			logger.error("出错了" + e.getMessage());
		}
		return result;
	}

	/**
	 * 
	 * 启动作业用runJob
	 * @param jobName
	 * @return id
	 */
	public static String runJob(String carte, String jobName) {
		
		String id = null;
		try {
			carte = "http://192.168.10.143:8085";
			//获取kettle的URL
			String urltemp = carte + "/kettle/runJob/?job=";
//			String urltemp = carte + "/kettle/executeJob/?rep=130&user=admin&pass=admin&job=";
			String urltemp1 = jobName;
			String uri = urltemp + urltemp1;
			HttpGet get = new HttpGet(uri);
			logger.info(uri);
			//添加http头信息
			get.addHeader("Authorization", "Basic Y2x1c3RlcjpjbHVzdGVy");
//	        get.setHeader("Cache-Control", "max-age=0");
//	        get.addHeader("User-Agent","your agent");
			HttpResponse response;
			response = httpClient.execute(get);
			int code = response.getStatusLine().getStatusCode();
			//检验状态码，如果成功接收数据
			if (code == 200) {
				String rev = EntityUtils.toString(response.getEntity());
				DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  
				DocumentBuilder builder = factory.newDocumentBuilder();  
				ByteArrayInputStream is = new ByteArrayInputStream(rev.getBytes());
				Document doc = builder.parse(is);
				NodeList nodeList = doc.getElementsByTagName("result");
				NodeList idList = doc.getElementsByTagName("id");
				Node node = nodeList.item(0);
				Node idnode = idList.item(0);
                id = idnode.getTextContent();
				logger.info(node.getTextContent());
				logger.info(id);
				logger.info(response);
				logger.info(jobName + "启动成功" +rev);
				
			}
		} catch (Exception e) {
			logger.error("出错了" + e.getMessage());
		}
		return id;
	}
	
	/**
	 * 
	 * 启动作业用runJob
	 * @param jobNameParam
	 * @return id
	 * @throws Exception 
	 */
	public static String runJobParam(String carte, Map<String, String> dtoInput) throws Exception {
		
		String result = null;
		String id = null;
		try {
			//获取kettle的URL
			String urltemp = carte + "/kettle/runJob/";
			String uri = urltemp;
			HttpPost post = new HttpPost(uri);
			logger.info(uri);
			//添加http头信息
			post.setHeader("Authorization", "Basic Y2x1c3RlcjpjbHVzdGVy");
			post.setHeader("Content-Type", "application/x-www-form-urlencoded");
			post.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.26 Safari/537.36 Core/1.63.6726.400 QQBrowser/10.2.2265.400");
			//设置参数
            List<NameValuePair> parameters = new ArrayList<NameValuePair>(); 
    		for (Iterator<String> iter = dtoInput.keySet().iterator(); iter.hasNext();) {
    			String name = (String) iter.next();
    			String value = String.valueOf(dtoInput.get(name));
    			parameters.add(new BasicNameValuePair(name, value));
    		}

			HttpEntity entity = new UrlEncodedFormEntity(parameters,"UTF-8");
			post.setEntity(entity);
			HttpResponse response;
			response = httpClient.execute(post);
			int code = response.getStatusLine().getStatusCode();
			//检验状态码，如果成功接收数据
			if (code == 200) {
				String rev = EntityUtils.toString(response.getEntity(), "UTF-8");
				DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  
				DocumentBuilder builder = factory.newDocumentBuilder();  
				ByteArrayInputStream is = new ByteArrayInputStream(rev.getBytes("UTF-8"));
				Document doc = builder.parse(is);
				NodeList nodeList = doc.getElementsByTagName("result");
				NodeList idList = doc.getElementsByTagName("id");
				Node node = nodeList.item(0);
				Node idnode = idList.item(0);
				result = node.getTextContent();
				id = idnode.getTextContent();
				if (!"OK".equals(result)) {
					throw new Exception(rev);
				}
				logger.info(result);
				logger.info(id);
				logger.info(response.toString());
				logger.info(dtoInput.get("jobName") + "启动成功" +rev);
				
			}
		} catch (Exception e) {
			logger.error("出错了" + e.getMessage());
			throw e;
		}
		return id;
	}

	/**
	 * 
	 * @param jobName
	 * @param jobId
	 * @return status
	 */
	public static String jobStatus(String carte, String jobName, String jobId) {
		String result = "";
		try {
			carte = "http://192.168.10.141:8085";
			//获取kettle的URL
			String urltemp = carte + "/kettle/jobStatus/?xml=Y&name=";
			//目标URL    Transformation name
			String urltemp1 = jobName;
			String id ="";
			if(StringUtils.isNotBlank(jobId)) {
				id = "&id=" +jobId;
			}
			String uri = urltemp + urltemp1 + id;
			HttpGet get = new HttpGet(uri);
			logger.info(uri);
			//添加http头信息
			get.addHeader("Authorization", "Basic Y2x1c3RlcjpjbHVzdGVy");
			HttpResponse response;
			response = httpClient.execute(get);
			int code = response.getStatusLine().getStatusCode();
			//检验状态码，如果成功接收数据
			if (code == 200) {
				String rev = EntityUtils.toString(response.getEntity());
				DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  
				DocumentBuilder builder = factory.newDocumentBuilder();  
				ByteArrayInputStream is = new ByteArrayInputStream(rev.getBytes());
				Document doc = builder.parse(is);
				NodeList nodeList = doc.getElementsByTagName("status_desc");
				Node node = nodeList.item(0);
				result = node.getTextContent();
				logger.info(jobName + "作业状态是：" + node.getTextContent());
				logger.info(id);
				logger.info(response);
				logger.info(rev);
				
			}
		} catch (Exception e) {
			logger.error("出错了" + e.getMessage());
		}
		return result;
	}
	public static String carteStatus(String carte) {
		String result = "";
		try {
			carte = "http://192.168.10.141:8085";
			//获取kettle的URL
			String urltemp = carte + "/kettle/status/?xml=Y";
			String uri = urltemp;
			HttpGet get = new HttpGet(uri);
			logger.info(uri);
			//添加http头信息
			get.addHeader("Authorization", "Basic Y2x1c3RlcjpjbHVzdGVy");
			HttpResponse response;
			response = httpClient.execute(get);
			int code = response.getStatusLine().getStatusCode();
			//检验状态码，如果成功接收数据
			if (code == 200) {
				String rev = EntityUtils.toString(response.getEntity());
				DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  
				DocumentBuilder builder = factory.newDocumentBuilder();  
				ByteArrayInputStream is = new ByteArrayInputStream(rev.getBytes());
				Document doc = builder.parse(is);
				NodeList nodeList = doc.getElementsByTagName("statusdesc");
				Node node = nodeList.item(0);
				result = node.getTextContent();
				logger.info("carte状态是：" + node.getTextContent());
				logger.info(response);
				logger.info(rev);
				
			}
		} catch (Exception e) {
			logger.error("出错了" + e.getMessage());
			return "Offline";
		}
		return result;
	}

	public static void main(String[] args) {
//		CarteKettleRunTest.executeTrans("性能测试_国君环境_文件到库");
//		String transId = CarteKettleRunTest.runTrans("","insert_update");
//		logger.info("启动的transId是：" + transId);
//		CarteKettleRunTest.transStatus("","insert_update","");
//		String jobId = CarteKettleRunTest.runJob("","TEST1");
//		logger.info("启动的jobId是：" + jobId);
//		CarteKettleRunTest.jobStatus("","发送邮件job","9c9c965b-0d5f-4b36-8283-39d729293739");
//		CarteKettleRunTest.carteStatus("");
		String job = "TEST1";
		Map<String, String> dtoInput = new HashMap<String, String>();
		dtoInput.put("job", job);
		dtoInput.put("level", "Debug");
		dtoInput.put("YYYYMMDD", "20181015");
		String jobId = null;
		try {
			jobId = CarteKettleRunTest.runJobParam("http://192.168.10.143:8085",dtoInput);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		logger.info("启动的jobId是：" + jobId);
	}
}